<?php
class ParameterController extends CController {

	const PAGE_SIZE = 10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction = 'list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array (// perform access control for CRUD operations
			'accessControl'
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
			array (
				'allow', // allow all users to perform 'list' and 'show' actions
				'actions' => array (
					'list',
					'show'
				),
				'users' => array (
					'*'
				)
			),
			array (
				'allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions' => array (
					'create',
					'update',
					'admin',
					'delete',
					'headerJs'
				),
				'expression' => '!$user->isGuest && $user->isAdministrator()'
			),
			array (
				'deny', // deny all users
				'users' => array (
					'*'
				)
			)
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow() {
		$p = new ParameterForm($this->loadParameter());
		//		$p = $this->loadParameter();
		$this->render('show', array (
			'model' => $p
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate() {
		$model = new ParameterForm();

		if (!isset ($_POST['ParameterForm'])) {
			$this->render('create', array (
				'model' => $model,
				'update' => false,
				'step' => ''
			));
		} else {
			$model->attributes = $_POST['ParameterForm'];
			$this->render('create', array (
				'model' => $model,
				'update' => false,
				'step' => $model->param_type
			));
		}
		/*
		$model->user_type = Constants::ADVISER_USER_TYPE;
		
		if (!isset ($_POST['UserForm']) && !isset ($_POST['AdviserForm'])) {
			$this->render('create', array (
				'model' => $model,
				'step' => Constants::TYPE_USER_TYPE
			));
		} else {
			$arr = null;
			if (isset ($_POST['UserForm'])) {
				$arr = $_POST['UserForm'];
			}
			if (isset ($_POST['AdviserForm'])) {
				$arr = $_POST['AdviserForm'];
			}
		
			if ($arr == null) {
				$this->render('create', array (
					'model' => $model,
					'step' => Constants::TYPE_USER_TYPE
				));
			} else {
				if ($arr['user_type'] == Constants::ADVISER_USER_TYPE)
					$model = new AdviserForm();
				else
					$model = new UserForm();
				$model->scenario = UserForm::CREATE;
		
				if (isset ($arr['username'])) {
					$model->attributes = $arr;
					$model->validate();
					if (!$model->hasErrors()) {
						$this->redirect(array (
							'show',
							'id' => $model->username
						));
					} else {
						$this->render('create', array (
							'model' => $model,
							'step' => $model->user_type
						));
					}
				} else {
					$this->render('create', array (
						'model' => $model,
						'step' => $model->user_type
					));
				}
			}
		}*/
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate() {
		$user = $this->loadParameter();
		$model = new UserForm(false);
		$model->attributes = $user->attributes;

		if (Constants::findUserType($user) == Constants::ADVISER_USER_TYPE) {
			$model = new AdviserForm(false);
			$model->attributes = $user->attributes;
			$model->attributes = $user->adviser->attributes;
		}
		$model->administrator = $user->user_group == Constants::ADMIN_USER;
		$model->scenario = UserForm::UPDATE;

		$arr = null;

		if (isset ($_POST['UserForm']))
			$arr = $_POST['UserForm'];

		if (isset ($_POST['AdviserForm']))
			$arr = $_POST['AdviserForm'];

		if ($arr == null) {
			$this->render('update', array (
				'model' => $model,
				'step' => $model->user_type
			));
		} else {
			$model->attributes = $arr;
			$model->validate();
			if (!$model->hasErrors()) {
				$this->redirect(array (
					'show',
					'id' => $model->username
				));
			} else {
				$this->render('update', array (
					'model' => $model,
					'step' => $model->user_type
				));
			}
		}
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete() {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadParameter()->delete();
			$this->redirect(array (
				'list'
			));
		} else
			throw new CHttpException(400, Yii::t('user', 'Invalid request. Please do not repeat this request again.'));
	}

	/**
	 * Lists all models.
	 */
	public function actionList() {
		$models = Yii::app()->parameter->getAllParameterDescriptions();

		$this->render('list', array (
			'models' => $models
		));
	}

	public function actionHeaderJs() {
		if (isset ($_GET['mnemonic'])) {
			$p = null;
			try {
				$p = $this->loadParameter($_GET['mnemonic']);
			} catch (CHttpException $e) {

			} catch (CParameterException $e) {

			}
			Header("content-type: application/x-javascript");
?>
function Header(mnemonic, label, index, type, key, index_th = null)
{
	this.mnemonic = mnemonic;
	this.label = label;
	this.index = index;
	this.type = type;
	this.key = key;
	if (index_th == null)
		this.index_th = index;
	else
		this.index_th = index_th;
}

function HeaderException(field, message)
{
	this.field = field;
	this.message = message;
}

function HeaderList()
{
	var headers = new Array();
	this.AddHeader = function(header)
	{
		if (header.mnemonic === "" || header.mnemonic === undefined || header.mnemonic === null) 
		throw new HeaderException("mnemonic", "Mnemonic cannot be empty");
		if (header.label === "" || header.label === undefined || header.label === null) 
		throw new HeaderException("label", "Label cannot be empty");
		if (header.index === "" || header.index === undefined || header.index === null) 
		throw new HeaderException("index", "Index cannot be empty");
		if (header.type === "" || header.type === undefined || header.type === null) 
		throw new HeaderException("type", "Type cannot be empty");
		if (header.key === "" || header.key === undefined || header.key === null) 
		throw new HeaderException("key", "Key cannot be empty");
	
		if( headers[header.mnemonic] !== undefined ) 
			throw new HeaderException("mnemonic", "Duplicate entry "+header.mnemonic);
		
		headers[header.mnemonic] = header;
	}
	
	this.UpdateHeader = function(mnemonic, header)
	{
		if (header.mnemonic === "" || header.mnemonic === undefined || header.mnemonic === null) 
		throw new HeaderException("mnemonic", "Mnemonic cannot be empty");
		if (header.label === "" || header.label === undefined || header.label === null) 
		throw new HeaderException("label", "Label cannot be empty");
		if (header.index === "" || header.index === undefined || header.index === null) 
		throw new HeaderException("index", "Index cannot be empty");
		if (header.type === "" || header.type === undefined || header.type === null) 
		throw new HeaderException("type", "Type cannot be empty");
		if (header.key === "" || header.key === undefined || header.key === null) 
		throw new HeaderException("key", "Key cannot be empty");
	
		if( headers[mnemonic] === undefined ) 
			throw new HeaderException("mnemonic", "Cannot find entry "+mnemonic);
		
		if( headers[header.mnemonic] !== undefined && header.mnemonic != mnemonic ) 
			throw new HeaderException("mnemonic", "Duplicate entry "+header.mnemonic);
		
		headers[mnemonic] = undefined;
		headers[header.mnemonic] = header;
	}
	
	this.GetHeader = function(mnemonic)
	{
		return headers[mnemonic];
	}
	
	this.GetHeaders = function()
	{
		return headers;
	}
}

var headers = new HeaderList();
<?php

			if ($p != null) {
				foreach ($p->headers as $header)
					:
?>
HeaderList.AddHeader(new Header(
	'<?php echo $header['mnemonic']; ?>',
	'<?php echo $header['label']; ?>',
	'<?php echo $header['index']; ?>',
	'<?php echo $header['type']; ?>',
	'<?php echo $header['key'] ? 'true' : 'false'; ?>'
));
<?php
 endforeach;
			}
		}
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$this->processAdminCommand();

		$criteria = new CDbCriteria;

		$pages = new CPagination(user::model()->count($criteria));
		$pages->pageSize = self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort = new CSort('user');
		$sort->applyOrder($criteria);

		$models = user::model()->findAll($criteria);

		$this->render('admin', array (
			'models' => $models,
			'pages' => $pages,
			'sort' => $sort
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadParameter($mnemonic = null) {
		if ($this->_model === null) {
			if ($mnemonic !== null || isset ($_GET['mnemonic']))
				$this->_model = Yii::app()->parameter->getParametersArray($mnemonic !== null ? $mnemonic : $_GET['mnemonic']);
			if ($this->_model === null)
				throw new CHttpException(404, Yii::t('parameter', 'The requested page does not exist.<br />No parameter found for mnemonic {mnemonic}.', array (
					'{mnemonic}' => $mnemonic !== null ? $mnemonic : $_GET['mnemonic']
				)));
		}
		return $this->_model;
	}

	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand() {
		if (isset ($_POST['command'], $_POST['id']) && $_POST['command'] === 'delete') {
			$this->loadParameter($_POST['id'])->delete();
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}
}
?>
